<template>
    <n-card :bordered="false" class="proCard">
        <BasicTable :title="courseName" titleTooltip="可爱捏" :columns="columns" :request="loadDataTable"
            :row-key="(row) => row.id" ref="actionRef" :actionColumn="actionColumn" :scroll-x="1360"
            :row-class-name="rowClassName" @update:checked-row-keys="onCheckedRow">
            <template #tableTitle v-if="route.params.courseID != null">
                <n-space>
                    <n-button type="primary" @click="addTable">
                        <template #icon>
                            <n-icon>
                                <PlusOutlined />
                            </n-icon>
                        </template>
                        添加学生
                    </n-button>
                    <n-button type="primary" @click="addClaseTable">
                        <template #icon>
                            <n-icon>
                                <PlusOutlined />
                            </n-icon>
                        </template>
                        班级添加
                    </n-button>
                    <n-button type="primary" color="#27ae60" @click="showExcelModal = true">
                        <template #icon>
                            <n-icon>
                                <PlusOutlined />
                            </n-icon>
                        </template>
                        Excel导入
                    </n-button>
                    <n-button tag="a" type="primary" href="/api/index/getCourseExcelModal">
                        下载导入模板
                </n-button>
                </n-space>
            </template>
            <template #toolbar>
                <n-button type="primary" @click="reloadTable">刷新数据</n-button>
            </template>
        </BasicTable>
        <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" :title="title">
            <n-form :model="formParams" :rules="rules" ref="formRef" label-placement="left" :label-width="80"
                class="py-4">
                <n-form-item label="学号" path="SID">
                    <n-input placeholder="请输入学号" v-model:value="formParams.SID" />
                    <n-button @click="handleCheckStudent">查询学生</n-button>
                </n-form-item>
                <n-form-item label="学生名" path="studentName">
                    <n-input placeholder="" readonly v-model:value="formParams.studentName" />
                </n-form-item>
            </n-form>
            <template #action>
                <n-space>
                    <n-button @click="() => (showModal = false)">取消</n-button>
                    <n-button type="info" :loading="formBtnLoading" @click="confirmForm">确定</n-button>
                </n-space>
            </template>
        </n-modal>
        <n-modal v-model:show="showClaseModal" :show-icon="false" preset="dialog" title="班级添加">
            <n-form :model="claseFormParams" :rules="claseRules" ref="claseFormRef" label-placement="left"
                :label-width="80" class="py-4">
                <n-form-item label="学院" path="academyID">
                    <n-select v-model:value="claseFormParams.academyID" :options="academyOptions"
                        @update:value="handleFormAcademyUpdate"></n-select>
                </n-form-item>
                <n-form-item label="专业" path="majorID">
                    <n-select v-model:value="claseFormParams.majorID" :options="formMajorOptions"
                        @update:value="handleFormMajorUpdate"></n-select>
                </n-form-item>
                <n-form-item label="班级" path="claseID">
                    <n-select v-model:value="claseFormParams.claseID" :options="formClaseOptions"></n-select>
                </n-form-item>
            </n-form>
            <template #action>
                <n-space>
                    <n-button @click="() => (showClaseModal = false)">取消</n-button>
                    <n-button type="info" :loading="formBtnLoading" @click="confirmClaseForm">确定</n-button>
                </n-space>
            </template>
        </n-modal>
        <n-modal v-model:show="showExcelModal" :show-icon="false" preset="dialog" title="Excel插入">
            <n-button :disabled="!fileListLengthRef" style="margin-bottom: 12px" @click="uploadRef?.submit()">
                上传文件
            </n-button>
            <n-upload ref="uploadRef" :action="uploadUrl" :default-upload="false" :max="1" @change="handleChange"
                :headers="header" @finish="handleUploadFinish" @error="handleUploadError">
                <n-button>选择文件</n-button>
            </n-upload>
            <template #action>
                <n-space>
                    <n-button @click="() => (showExcelModal = false)">取消</n-button>
                </n-space>
            </template>
        </n-modal>
    </n-card>
</template>
<script lang="ts" setup>
import { reactive, ref, h, onMounted } from 'vue';
import { getTableList } from '@/api/manager/courseManage/studentList';
import { BasicTable, TableAction } from '@/components/Table';
import { columns } from './student';
import { PlusOutlined } from '@vicons/antd';
import { SelectOption, UploadFileInfo, UploadInst, useDialog, useMessage } from 'naive-ui';
import { http } from '@/utils/http/axios';
import { useRoute } from 'vue-router';
import { createStorage } from '@/utils/Storage';
const Storage = createStorage({ storage: localStorage });
const route = useRoute();
console.log(route.params.value)

const params = reactive({
    pageSize: 10,
    courseID: route.params.courseID
});
const showModal = ref(false);
const rules = {
    SID: {
        required: true,
        trigger: ['blur', 'input'],
        message: '请输入学号',
    },
};

const claseRules = [

]

const formParams: any = reactive({
    SID: null,
    studentName: null
});

const claseFormParams: any = reactive({
    academyID: null,
    majorID: null,
    claseID: null
});


const formRef = ref();
const claseFormRef = ref();
const formBtnLoading = ref(false);
const title = ref("");
const message = useMessage();
const dialog = useDialog();
const courseName = route.params.courseName ? route.params.courseName : '学生课程列表';
const showClaseModal = ref(false);

const academyOptions = ref<SelectOption[]>([]);
const formMajorOptions: any = ref<SelectOption[]>([]);
const formClaseOptions = ref<SelectOption[]>([]);

const showExcelModal = ref(false);
const uploadRef = ref<UploadInst | null>(null)
const fileListLengthRef = ref(0)
const header = {
    Authorization: Storage.get("ACCESS-TOKEN", ''),
}
const uploadUrl = ref("/api/manager/student_course_manage/excelInsertStudent?courseID="+route.params.courseID);

function handleChange (options: { fileList: UploadFileInfo[] }) {
        fileListLengthRef.value = options.fileList.length
      }

const handleUploadFinish=({
      file,
      event
    }: {
      file: UploadFileInfo
      event?: ProgressEvent
    }) => {
      let response = JSON.parse((event?.target as XMLHttpRequest).response);
      if(response.code == 200){
        message.success("成功!");
        showExcelModal.value = false;
      }else{
        message.error(response.message);
      }
      reloadTable();
      return file
    }
function handleUploadError(){
    message.error('上传失败');
}

onMounted(
    async () => {
        const academyMajorInfo = ref();
        academyMajorInfo.value = await http.request({
            url: '/manager/academy_major_manage/list',
            method: 'get',
        });
        academyMajorInfo.value.forEach(element => {
            academyOptions.value.push({
                label: element['academyName'],
                value: element['academyID'],
                majorList: ((element) => {
                    let arr: any = [];
                    element['majorList'].forEach(element => {
                        arr.push(
                            {
                                label: element['majorName'],
                                value: element['majorID'],
                            })
                    });
                    return arr;
                })(element),
            });
        });
        //获取学院信息
    })

function handleFormAcademyUpdate(e: any, s: any) {
    e;
    if (s) {
        formMajorOptions.value = s['majorList'];
    } else {
        formMajorOptions.value = [
            {
                label: '',
                value: ''
            }
        ];
    }
    claseFormParams.majorID = null;
    claseFormParams.claseID = null;
}

async function handleFormMajorUpdate() {
    claseFormParams['claseID'] = null;
    //清空专业字段
    let params = claseFormParams;
    let claseInfo = await http.request({
        url: '/manager/clase_manage/list',
        method: 'get',
        params
    })
    formClaseOptions.value = [];
    claseInfo.forEach(element => {
        formClaseOptions.value.push({
            label: element['claseName'],
            value: element['claseID'],
        });
    });
}


function confirmForm(e) {
    e.preventDefault();
    formBtnLoading.value = true;
    formRef.value.validate((errors) => {
        if (!errors) {
            //message.success('新建成功');
            let params = formParams;
            params['courseID'] = route.params.courseID;
            let url = '/manager/student_course_manage/add';
            http.request({
                url: url,
                method: 'post',
                params
            }).then(
                () => {
                    message.success('成功');
                    showModal.value = false;
                    reloadTable();
                }
            );
        } else {
            message.error('请填写完整信息');
        }
        formBtnLoading.value = false;
    });
}

function confirmClaseForm(e) {
    e.preventDefault();
    formBtnLoading.value = true;
    claseFormRef.value.validate((errors) => {
        if (!errors) {
            //message.success('新建成功');
            let params = claseFormParams;
            params['courseID'] = route.params.courseID;
            let url = '/manager/student_course_manage/addClase';
            http.request({
                url: url,
                method: 'post',
                params
            }).then(
                () => {
                    message.success('成功');
                    showClaseModal.value = false;
                    reloadTable();
                }
            );
        } else {
            message.error('请填写完整信息');
        }
        formBtnLoading.value = false;
    });
}

const loadDataTable = async (res) => {
    return await getTableList({ ...params, ...res });
};

async function handleCheckStudent() {
    if (formParams['SID'] == null) {
        message.error('请填写学生学号');
        return;
    }
    let studentInfo = await http.request({
        url: '/manager/student_manage/getStudentName',
        method: 'get',
        params: { SID: formParams['SID'], courseID: route.params.courseID }
    });
    formParams['studentName'] = studentInfo.claseName + ' ' + studentInfo['name'];
}

const actionColumn = reactive({
    width: 250,
    title: '操作',
    key: 'action',
    fixed: 'right',
    align: 'center',
    render(record) {
        return h(TableAction, {
            style: 'button',
            actions: createActions(record),
        });
    },
});

function handleDelete(record) {
    console.log(record);
    dialog.info({
        title: '提示',
        content: `您想删除${record.courseName}`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: () => {
            //message.success('删除成功');
            let getparam = {};
            let url = "/manager/student_course_manage/delete";
            getparam['SID'] = record['SID'];
            getparam['courseID'] = record['courseID'];

            http.request({
                url: url,
                method: 'get',
                params: getparam
            }
            ).then(
                () => {
                    message.success('成功');
                    reloadTable();
                }
            );
        },
        onNegativeClick: () => { },
    });
}

// function handleEdit(row) {
//     formParams.courseID = row.courseID;
//     formParams.courseName = row.courseName;
//     formParams.TID = row.TID;
//     formParams.teacherName = row.name;
//     title.value = '修改';
//     isReadOnly.value = true;
//     showModal.value = true;
// }

function rowClassName(row) {
    console.log(row);
    if (row.majorList != null) {
        return '';
    } else {
        return 'leaf-row'
    }
}

function createActions(record) {
    return [
        {
            label: '删除',
            icon: 'ic:outline-delete-outline',
            onClick: handleDelete.bind(null, record),
            // 根据业务控制是否显示 isShow 和 auth 是并且关系
            ifShow: () => {
                return true;
            },
            // 根据权限控制是否显示: 有权限，会显示，支持多个
            auth: ['basic_list'],
        },

    ];
}
const actionRef = ref();
function onCheckedRow() {

}
function addTable() {
    formParams.SID = null;
    title.value = '新建';
    showModal.value = true;
}

function addClaseTable() {
    showClaseModal.value = true;
}

function reloadTable() {
    actionRef.value.reload();
}

</script>
